﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRMSimple.LogService.DataProducter.Abstractions;
using CRMSimple.LogService.DataConsumer.Abstractions;
using CRMSimple.LogService.DataCache.Abstractions;
using System.Threading;
using BitAuto.EP.CRMLogSystem.Utils;
using BitAuto.EP.Plat.Util;

namespace CRMSimple.LogServices
{
    public class LogServiceContextRoot 
    {
        private IDataProducter _producter;
        private IDataConsumer _consumer;
        private IDataCache _cache;

        private bool isStop = false;
        private CancellationTokenSource cts = new CancellationTokenSource();
        private CancellationTokenSource cts1 = new CancellationTokenSource();

        private Action BuildProducterStart(IDataProducter producter, IDataConsumer consumer)
        {
            return () =>
            {
                producter.StartProduceData(consumer.ConsumeData);
            };
        }
        private Action<object> BuildProducterStart(IDataProducter producter, IDataCache cache)
        {
            //return new Task(() =>
            //{
            //    try
            //    {
            //        _producter.StartProduceData(_cache.Set);
            //    }
            //    catch (Exception ex)
            //    {
            //        string content = string.Format("生产数据异常");
            //        DataLogHelper.E(content,ex);
            //        ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message+ex.StackTrace);
             
            //    }
               
            //}, cts.Token,TaskCreationOptions.AttachedToParent);
            return (e) =>
            {
                try
                {
                    _producter.StartProduceData(_cache.Set);
                    LogExceptionRoot.DataProducterLog.Info("生产数据服务启动");
                }
                catch (Exception ex)
                {
                    string content = string.Format("生产数据异常");
                    //DataLogHelper.E(content, ex);
                    LogExceptionRoot.DataProducterLog.Info(content, ex);
                    ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message + ex.StackTrace);

                }

            };
        }
        private Action BuildProducterStop(IDataProducter producter)
        {
            return () =>
            {
                _producter.StopProduceData();
                //cts.Cancel();
                LogExceptionRoot.DataProducterLog.Info("生产数据服务停止");
            };
        }
        private Action<object> BuildConsumerStart(IDataConsumer consumer, IDataCache cache)
        {
            //return new Task(() =>
            //{
            //    while (!isStop)
            //    {
            //        try
            //        {
            //            _cache.Get(_consumer.ConsumeData);
            //        }
            //        catch (Exception ex)
            //        {
                        
            //            string content = string.Format("消费数据异常");
            //            DataLogHelper.E(content,ex);
            //            ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message+ex.StackTrace);
            //        }
                    
            //        //执行完一轮，休眠
            //        Thread.Sleep(EConvert.ToInt(AppConfig.GetAppSetting("ReadFile:SleepTime"), 10000));
            //    }
            //}, cts1.Token, TaskCreationOptions.AttachedToParent); 
            return (e) =>
            {
                LogExceptionRoot.DataConsumerLog.Info("消费服务启动");
                while (!isStop)
                {
                    //执行完一轮，休眠
                    Thread.Sleep(EConvert.ToInt(AppConfig.GetAppSetting("ReadFile:SleepTime"), 10000));
                    try
                    {
                        _cache.Get(_consumer.ConsumeData);
                    }
                    catch (Exception ex)
                    {

                        string content = string.Format("消费数据异常");
                        //DataLogHelper.E(content, ex);
                        LogExceptionRoot.DataConsumerLog.Info(content, ex);
                        ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message + ex.StackTrace);
                    }

                   
                }
            }; 
        }

        public void SetProducter(IDataProducter producter)
        {
            this._producter = producter;
        }
        public void SetCache(IDataCache cache)
        {
            this._cache = cache;
        }
        public void SetConsumer(IDataConsumer consumer)
        {
            this._consumer = consumer;
        }

        public void RunTest()
        {
            BuildProducterStart(this._producter, this._cache)(null);
            BuildConsumerStart(this._consumer, this._cache)(null);
        }
        public LogServiceContextRoot Buid()
        {
            //
            if (_producter != null && _cache != null)
            {
                this.Run = BuildProducterStart(this._producter, this._cache);
                this.Stop = BuildProducterStop(this._producter);
            }
            if (_consumer != null && _cache != null)
            {
                this.Run = BuildConsumerStart(this._consumer, this._cache);
                this.Stop = () => { this.isStop = true; LogExceptionRoot.DataConsumerLog.Info("消费服务停止动"); };
            }

            return this;
        }
        public Action<object> Run
        {
            get;
            private set;
        }
        public Action Stop
        {
            get;
            private set;
        }
    }
}
